
local LOG = require 'guac.log'

LOG:info("----------------------------------------------------")
LOG:info("Starting up...")

local lfs = require 'lfs'
local guac = require 'guac'
local dialog = require 'guac.dialog'

-- make package.path and package.cpath absolute, so we can change
-- working directories later:

local function absolutepath(p)
  return string.gsub(p, '[^;]+',
    function(v)
      return lfs.currentdir() .. '/' .. v
    end)
end

package.cpath = absolutepath(package.cpath)
package.path = absolutepath(package.path)

local project_file = dialog.choosefile{
  mode = 'open';
  filters = {
    {display='Project main files (*.main.lua)', patterns={'*.main.lua'}};
    {display='All Lua files (*.lua)', patterns={'*.lua'}};
    {display='All files', patterns={'*.*'}};
  };
}

if (project_file == nil) then
  -- user cancelled
  LOG:fatal("No project main file selected.")
  return
end

LOG:info("File selected: " .. project_file)

if (lfs.attributes(project_file, 'mode') ~= 'file') then
  dialog.alert("Invalid project file")
end

local dir = string.match(project_file, '^(.*[\\/])[^\\/]+')

lfs.chdir(dir)

package.loaded.F = function(rel_path)
  return dir .. rel_path
end

local script, message = loadfile(project_file)
if not script then
  dialog.alert(tostring(message))
  LOG:fatal("Parse Error:")
  LOG:fatal(message)
  return
end

-- Do not prefix a location onto an error message
local _error = error
function error(msg)
  return _error(msg, 0)
end

local success, message = xpcall(script, guac.fatalerrorhandler)

if not success then
  return
end

LOG:info("Shutting down.")
